//
//  YAPicBrowserCell.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/14.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
/// 照片cell的协议
protocol YAPicBrowserCellDelegate:NSObjectProtocol{
    //MARK:--- 告诉控制器被缩放完成
    func photoBrowserCellDidZoomed()
     //MARK:--- 告诉控制器被缩放的比例
    func photoBrowserCellDidZooming(scale:CGFloat)
}
class YAPicBrowserCell: UICollectionViewCell {
     //MARK:--- 照片缩放的代理
    weak var photoDelegate:YAPicBrowserCellDelegate?
     //MARK:--- 添加cell数据属性，接收URL 
    var url:NSURL?{
        //打开指示器
        didSet{
            //设置图片重置scrollView，消除上次缩放时对scrollView做出的改变
            reSetScrollView()
            indicator.startAnimating()
            imageView.image = nil
            //模拟延迟效果
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0*NSEC_PER_SEC)),dispatch_get_main_queue()) { () -> Void in
                //用SDWebImage将图片缓存到本地,为了自适应图片大小用下面的方法
                self.imageView.sd_setImageWithURL(self.url, placeholderImage: nil, options: SDWebImageOptions.RetryFailed) { (image, error, _, _) -> Void in
                    //self.imageView.sizeToFit()//自适应，有可能会超过cell的大小
                    self.indicator.stopAnimating()
                    //判断图像是否下载完成
                    if error != nil {
                        SVProgressHUD.showInfoWithStatus("您的网络不给力")
                        return
                    }
                    //调整图片大小，大小 坐标在0点
                    self.setImagePosition()
            }
            }
        }
    }
   //MARK:--- 重置srollView
    private func reSetScrollView(){
        scrollView.contentSize = CGSizeZero
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        //重置imageView形变属性
        imageView.transform = CGAffineTransformIdentity
    }
 //MARK:--- 长短图处理
    private func setImagePosition(){
        let size = displaySize(imageView.image!)
        imageView.frame = CGRect(origin: CGPointZero, size: size)
        if size.height < scrollView.bounds.height{
            let y = (scrollView.bounds.height - size.height)*0.5
//            imageView.frame = CGRect(x: 0, y: y, width: size.width, height: size.height)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }else
        {
            
            scrollView.contentSize = size//这个时候，可以滚动scrollView看完全图
        }
    }
     //MARK:--- 按照scrollView的宽度，计算缩放后的比例
    private func displaySize(image:UIImage)->CGSize{
        let scale = image.size.height/image.size.width
        let w = scrollView.bounds.width
        let h = w * scale
        return CGSize(width: w, height: h)
    }
     //MARK:--- 重写构造函数，添加和布局控件
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicator)//注意：为什么要放放在contentView上
        //让scrollView和cell一样大
        //scrollView.frame = bounds
        //实现cell边距效果
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        indicator.center = scrollView.center
        prepareScrollView()
    }
     //MARK:--- 准备scrollView
    private func prepareScrollView(){
        //设置代理
        scrollView.delegate = self
        //设置缩放比例
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
    }
     //MARK:--- 1.懒加载控件
    private lazy var scrollView = UIScrollView()//解决长图和捏合缩放需求
    //显示单张图片
    lazy var imageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    //菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}
//MARK: - 实现缩放的代理方法
extension YAPicBrowserCell:UIScrollViewDelegate{
     //MARK:--- 告诉scrollView缩放哪个视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
     //MARK:--- 缩放完成后调用的方法
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
//        printLog("---缩放完成后调用的方法--------------------")
//        //打印被缩放的视图
//        printLog(view)
//        //打印缩放完成后的比例
//        printLog(scale)
        //调整Y的值 
        var offSetY = (scrollView.bounds.height - imageView.frame.height)*0.5
        var offSetX = (scrollView.bounds.width - imageView.frame.width)*0.5
        //处理图片被放大到超过屏幕的情况
        offSetY = (offSetY < 0) ? 0 : offSetY
        offSetX = (offSetX < 0) ? 0:offSetX
        //重新设置间距
        scrollView.contentInset = UIEdgeInsets(top: offSetY, left: offSetX, bottom: 0, right: 0)
        photoDelegate?.photoBrowserCellDidZoomed()
    }
     //MARK:--- 缩放的时候调用的方法
    func scrollViewDidZoom(scrollView: UIScrollView) {
        printLog("---缩放的时候调用的方法-----bounds * transform => frame---------------")
        printLog(imageView.transform)
        printLog(imageView.bounds)//这个值始终不变
        printLog(imageView.frame)
        //告诉代理者缩放的比例
        photoDelegate?.photoBrowserCellDidZooming(imageView.transform.a)
    }
}